package service

import (
	"my_music_server/common"
	"my_music_server/common/utils"
	"my_music_server/dao"
	"my_music_server/model"
)

var _userDao dao.UserDao

type UserService struct {
}

func (u *UserService) Login(loginVO model.LoginVO) map[string]interface{} {
	if loginVO.UserName == "" {
		panic(common.ERROR_USER_NOTEXISTS)
		//panic(gin.H{"error":"test"})
	}

	if loginVO.PassWord == "" {
		panic(common.ERROR_USER_PWD)
	}

	var user model.User
	dao.DB.Where("user_name=?", loginVO.UserName).First(&user)

	//兼容性没有salt
	if user.Salt != "" {
		if !(utils.MD5(loginVO.PassWord+user.Salt) == user.Password) {
			panic(common.ERROR_USER_PWD)
		}
	} else {
		if !(utils.MD5(loginVO.PassWord) == user.Password) {
			panic(common.ERROR_USER_PWD)
		}
	}

	//生成token
	mp := map[string]interface{}{
		"id":           user.ID,
		"nickname":     user.NickName,
		"username":     user.UserName,
		"sex":          user.Sex,
		"phone":        user.Phone,
		"headerImgUrl": user.HeaderImgUrl,
	}

	tokenStr := utils.GenerateJWT(mp)
	//构建返回数据
	result := make(map[string]interface{})
	result["username"] = user.UserName
	result["userid"] = user.ID
	result["headerImgUrl"] = user.HeaderImgUrl
	result["token"] = tokenStr

	return result
}

func (u *UserService) Register(registerVo model.RegisterVo) bool {
	userName := registerVo.UserName
	nickName := registerVo.NickName
	phone := registerVo.Phone
	password := registerVo.Password
	sex := registerVo.Sex

	//校验参数
	if userName == "" || password == "" {
		panic(common.ERROR_PARAMETER)
	}

	//查看用户名是否被注册
	//var count int
	//var userOld model.User
	//dao.DB.Where("user_name=?", userName).Find(&userOld).Count(&count)
	count, _ := _userDao.GetUserCountByUserName(userName)
	if count > 0 {
		panic(common.ERROR_USER_EXIST)
	}

	//注册
	//生成盐
	uuidStr := utils.GetUUID()
	salt := string(uuidStr[:6])

	//dao.DB.Create(&model.User{
	//	UserName: userName,
	//	NickName: nickName,
	//	Sex:      sex,
	//	Password: utils.MD5(password + salt), //加盐加密
	//	Salt:     salt,
	//	Phone:    phone,
	//})

	_userDao.Insert(&model.User{
		UserName: userName,
		NickName: nickName,
		Sex:      sex,
		Password: utils.MD5(password + salt), //加盐加密
		Salt:     salt,
		Phone:    phone,
	})

	return true
}
